package model

import (
	"context"
	"fmt"

	"gorm.io/gorm"
)

type CommentSubject struct {
	gorm.Model
	ObjectId   uint
	ObjectType int `gorm:"default:0;column:object_type;check:object_type IN (0,1)"`
	UserId     int
	Count      int
	RootCount  int
}

// 确保主题存在（不存在则创建）
func (m *defaultCommentModel) EnsureSubject(ctx context.Context, objectID uint, objectType int, userID int) error {
	var count int64
	err := m.db.WithContext(ctx).Model(&CommentSubject{}).
		Where("object_id = ? AND object_type = ?", objectID, objectType).
		Count(&count).Error

	if err != nil {
		return fmt.Errorf("查询主题失败: %w", err)
	}

	if count == 0 {
		return m.db.WithContext(ctx).Create(&CommentSubject{
			ObjectId:   objectID,
			ObjectType: objectType,
			UserId:     userID,
			Count:      0,
			RootCount:  0,
		}).Error
	}
	return nil
}

func (m *defaultCommentModel) UpdateSubjectCount(ctx context.Context, objectID uint, objectType int, isRoot bool, count int) error {
	return m.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		// 更新总计数
		if err := tx.Model(&CommentSubject{}).
			Where("object_id = ? AND object_type = ?", objectID, objectType).
			UpdateColumn("count", gorm.Expr("count + ?", count)).
			Error; err != nil {
			return err
		}

		// 如果是根评论，更新根计数
		if isRoot {
			return tx.Model(&CommentSubject{}).
				Where("object_id = ? AND object_type = ?", objectID, objectType).
				UpdateColumn("root_count", gorm.Expr("root_count + ?", count)).
				Error
		}
		return nil
	})
}
